package com.zwz.crawler.mangeInfo.weburl;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class TungeeEnterpriseHomepage {
    private static final String ENTERPRISE_ID = "577de19eadf21dc4";

    public static void main(String[] args) {
        try {
            // 构建精准URL（带编码保护）
            String encodedId = URLEncoder.encode(ENTERPRISE_ID, String.valueOf(StandardCharsets.UTF_8));
            String url = "https://sales.tungee.com/api/enterprise/info/homepage?enterprise_id=" + encodedId;

            // 发送请求并处理编码
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
//                    .headers(getHeaders())
//                    .responseCharset("UTF-8") // 强制设置编码
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .execute();

            // 诊断编码问题
            diagnoseEncoding(response);

            // 处理响应
            processResponse(response);

        } catch (IOException e) {
            handleNetworkException(e);
        }
    }

//    private static Connection.Headers getHeaders() {
//        return new Connection.Headers()
//                .add("authority", "sales.tungee.com")
//                .add("accept", "*/*")
//                .add("accept-encoding", "gzip, deflate") // 禁用 zstd
//                .add("accept-language", "zh-CN,zh;q=0.9")
//                .add("cache-control", "no-cache")
//                .add("cookie", getCookies())
//                .add("pragma", "no-cache")
//                .add("priority", "u=1, i")
//                .add("referer", "https://sales.tungee.com/enterprise-details/"+ENTERPRISE_ID+"/enterprise-information/bussinesss-information")
//                .add("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
//                .add("sec-ch-ua-mobile", "?0")
//                .add("sec-ch-ua-platform", "\"Windows\"")
//                .add("sec-fetch-dest", "empty")
//                .add("sec-fetch-mode", "cors")
//                .add("sec-fetch-site", "same-origin")
//                .add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
//                .add("x-tonxis-pid", "67864ea75f69e05d3b544ca7");
//    }



    private static void diagnoseEncoding(Connection.Response response) {
       log.info("=== 编码诊断 ===");
       log.info("Content-Type: " + response.header("Content-Type"));
       log.info("实际字节长度: " + response.bodyAsBytes().length);

        // 对比不同编码的解码结果
        testDecoding(response.bodyAsBytes(), "UTF-8");
        testDecoding(response.bodyAsBytes(), "GBK");
    }

    private static void testDecoding(byte[] data, String charset) {
        try {
            String decoded = new String(data, charset);
           log.info("\n尝试用 " + charset + " 解码结果:");
           log.info(decoded.substring(0, Math.min(100, decoded.length())));
        } catch (Exception e) {
            System.err.println(charset + " 解码失败: " + e.getMessage());
        }
    }

    private static void processResponse(Connection.Response response) {
        String body = response.body();
       log.info("\n=== 响应处理 ===");
       log.info("状态码: " + response.statusCode());

        if (response.statusCode() == 200) {
           log.info("企业主页数据: \n" + body);
        } else {
            System.err.println("请求失败: " + body);
        }
    }

    private static void handleNetworkException(IOException e) {
        System.err.println("\n=== 网络异常 ===");
        if (e.getMessage().contains("Unable to resolve host")) {
            System.err.println("域名解析失败，请检查：");
            System.err.println("1. 网络连接状态");
            System.err.println("2. DNS设置（尝试 8.8.8.8）");
        } else {
            System.err.println("错误类型: " + e.getClass().getSimpleName());
            System.err.println("错误信息: " + e.getMessage());
        }
    }
}